package com.bizframework.springhb.support;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.xml.sax.InputSource;

public class DynamicLoadBean implements ApplicationContextAware {

	private ConfigurableApplicationContext applicationContext = null;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = (ConfigurableApplicationContext) applicationContext;
	}

	public ConfigurableApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 向spring的beanFactory动态地装载bean
	 * 
	 * @param configLocationString
	 *            要装载的bean所在的xml配置文件位置。 spring配置中的contextConfigLocation，同样支持诸如
	 *            "/WEB-INF/ApplicationContext-*.xml"的写法。
	 */
	public void loadBean(String configLocationString) {
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(
				(BeanDefinitionRegistry) getApplicationContext()
						.getBeanFactory());
		beanDefinitionReader.setResourceLoader(getApplicationContext());
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(
				getApplicationContext()));
		try {
			beanDefinitionReader.loadBeanDefinitions(getApplicationContext()
					.getResources(configLocationString));
		} catch (BeansException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void loadBeanByContent(String configLocationString) throws Exception {
		System.out.println(Thread.currentThread().getContextClassLoader()
				.getResource(""));
		File f = new File("C:/" + configLocationString);
		FileInputStream fis = new FileInputStream(f);
		
		int i = fis.available(); 
		byte abyte0[] = new byte[i]; 
		fis.read(abyte0); 
		
		String s = new String(abyte0); 
		StringReader sr = new StringReader(s);   
		
		InputSource inputSource = new InputSource(sr);
		inputSource.setSystemId("http://www.oreilly.com");
		inputSource.setEncoding("UTF-8");
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(
				(BeanDefinitionRegistry) getApplicationContext()
						.getBeanFactory());
		beanDefinitionReader.setResourceLoader(getApplicationContext());
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(
				getApplicationContext()));
		try {
			beanDefinitionReader.loadBeanDefinitions(inputSource);
			fis.close();
		} catch (BeansException e) {
			e.printStackTrace();
		}
	}
}